<?php


namespace App\Server;

use App\Models\Goods\Goods;
use App\Models\Goods\Type;
use Illuminate\Support\Facades\DB;

class GoodsCateService
{
    /**
     * 商品类型列表
     * @param $cate_name
     * @param int $limit
     * @return mixed
     */
    public function goodsCateList($cate_name,$limit=3){
        $where=[];
        if (!empty($where)){
            $where[]=['goods_name','like',"%$cate_name%"];
        }
        return Type::where($where)->paginate($limit);
    }

    /**
     * 过滤非法字段
     * @param $data
     * @param string $cate
     * @return mixed
     */
    public function data_filter($data,$cate='spec'){
        foreach ($data[$cate] as $ke => $v){
            //判断是否为空
            if (empty(trim($v['name']))){
                //删除当前整个名称对应的信息
                unset($data[$cate][$ke]);
                continue;
            }
            //
            foreach ($v['value'] as $k=>$va){
                if (empty(trim($va))){
                    //删除当前整个名称对应的信息
                    unset($data[$cate][$k]['value'][$k]);
                }
            }
            // 过滤之后没有值 删除当前数据
            if (count($data[$cate][$k]['value']) == 0) {
                unset($data[$cate][$k]);
            }
        }
        return $data;
    }

    /**
     * 规格、规格值、属性添加
     * @param $param
     */
    public function save($param){
        //启动事务
        DB::beginTransaction();
        try {
            $cate=Type::create(['type'=>$param['cate_name']]);
            //获取新增id
            $cate_id=$cate->id;
            //添加规格
            $spec=GoodsSpecService::save($param['spec'],$cate_id);
//            dd($spec);
            //添加规格值
            GoodsSpecService::specValueSave($spec,$param['spec'],$cate_id);
            //添加属性
            GoodsAttribute::save($param['attr'],$cate_id);//dd();
            DB::commit();//提交事务
        } catch (\Exception $exception){
            DB::rollBack();//回滚事务
            response()->json(['code'=>2002,'msg'=>'添加失败','data'=>[]]);
        }
    }

    /**
     * 删除
     * @param $id
     */
    public function delete($id){
        if (!is_numeric($id)){
            response()->json(['code'=>2001,'msg'=>'id只能是数字','data'=>[]]);
        }
        $Goods=Goods::where('type_id',$id)->select()->toArray();
        dd($Goods);
    }

    /**
     * 获取类型详情
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function detail($id){
        if (!is_numeric($id)){
            response()->json(['code'=>2001,'msg'=>'id只能是数字','data'=>[]]);
        }
        return Type::with(['attr','spec','spec.spec_values']);
//                ->visible(['attr'=>['id','attr_name','sort','type_id']])
//                ->hidden(['spec'=>['create_time','update_time','delete_time']])
//                ->find($id);
    }

}
